﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using EjemploSVN.Models;
using System.Collections;

namespace EjemploSVN.DataAccess
{
    public class HttpContextUnitOfWorkFactory : IUnitOfWorkFactory
    {
        private const string CurrentUnitOfWorkKey = "CurrentUnitOfWorkKey";

        public IUnitOfWork Current
        {
            get
            {
                IUnitOfWork uow = null;
                if (HttpContext.Current.Items.Contains(CurrentUnitOfWorkKey))
                {
                    uow = HttpContext.Current.Items[CurrentUnitOfWorkKey] as IUnitOfWork;
                }
                if (uow == null)
                {
                    uow = new DefaultUnitOfWork();
                    HttpContext.Current.Items[CurrentUnitOfWorkKey] = uow;
                }
                return uow;
            }
        }

        public IUnitOfWork DisposeUnitOfWork()
        {
            IDictionary contextItems = HttpContext.Current.Items; 
            IUnitOfWork uow = null;
            if (contextItems.Contains(CurrentUnitOfWorkKey))
            {
                uow = contextItems[CurrentUnitOfWorkKey] as IUnitOfWork;
                if (uow != null)
                    uow.Dispose();
                contextItems.Remove(CurrentUnitOfWorkKey);
            }
            return uow;

        }
    }
}